import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/Addons.js";
//引入UI控制器
import GUI from "lil-gui";
const gui = new GUI();

const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
};

//监听窗口变化事件
window.addEventListener("resize", () => {
  //   console.log(window.innerWidth);
  sizes.width = window.innerWidth;
  sizes.height = window.innerHeight;

  //调整相机
  camera.aspect = sizes.width / sizes.height;
  camera.updateProjectionMatrix(); //更新相机

  //调整渲染器
  renderer.setSize(sizes.width, sizes.height);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

//创建第一个场景
const scene = new THREE.Scene();

//创建物体
//几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
//材质
const material = new THREE.MeshBasicMaterial({ color: "orange" });
//创建网格
const cube = new THREE.Mesh(geometry, material);
//将网格添加到场景
scene.add(cube);

//创建摄像机
const camera = new THREE.PerspectiveCamera(60, sizes.width / sizes.height);
//相机位置
// camera.position.x = 2;
// camera.position.y = 2;
camera.position.z = 2;

camera.lookAt(cube.position);

// 将相机加入场景
scene.add(camera);

//创建渲染器材
const renderer = new THREE.WebGLRenderer();
renderer.setSize(sizes.width, sizes.height);
document.body.appendChild(renderer.domElement);

//控制器
//两个参数 要控制的相机 参考点--一般是渲染的画布
const controls = new OrbitControls(camera, renderer.domElement);
//可以更改看的轴的位置，但是需要同时调用update()
// controls.position.y = 2
// controls.update()

//开启阻尼效果，使更平缓
// 如果开启了阻尼，需要每帧都更新控制器
controls.enableDamping = true;

/*
    GUI控制面板
*/
//给物体cube添加一个颜色选择器
console.log(cube);

gui.addColor(cube.material, "color").name("Label");
gui.add(cube.position, "x", 0, 10, 1);
gui.add(cube.material, "wireframe");

const clock = new THREE.Clock();
const change = () => {
  //   let term = clock.getElapsedTime();
  //   cube.rotation.y = term;

  controls.update();

  renderer.render(scene, camera);
  window.requestAnimationFrame(change);
};
change();
